package com.hhf.rpa.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.rpa.file.config.FileConfig;
import com.hhf.rpa.file.mapper.BaseFileMapper;
import com.hhf.rpa.file.model.BaseFile;
import com.hhf.rpa.file.pojo.form.BaseFileForm;
import com.hhf.rpa.file.service.BaseFileService;
import com.hhf.rpa.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@Service
public class BaseFileServiceImpl extends ServiceImpl<BaseFileMapper, BaseFile> implements BaseFileService {

    public BaseFile saveFile(MultipartFile file, FileConfig fileConfig) {
        String storagePath = fileConfig.getStoragePath();
        String originalFilename = file.getOriginalFilename();
        Path path = Paths.get(storagePath, originalFilename);
        long size = file.getSize();
        BaseFile baseFile = new BaseFile();
        baseFile.setFileName(originalFilename);
        baseFile.setFileDir(storagePath);
        baseFile.setFullPath(path.toAbsolutePath().toString());
        baseFile.setUploadTime(new Date());
        baseFile.setFileSize(size);
        save(baseFile);
        return baseFile;
    }

    public boolean isExists(String fileName) {
        LambdaQueryWrapper<BaseFile> lqw = new LambdaQueryWrapper();
        lqw.eq(BaseFile::getFileName, fileName);
        Integer i = baseMapper.selectCount(lqw);
        if (i>0) {
            return true;
        }
        return false;
    }

    @Override
    public Page<BaseFile> selectPage(BaseFileForm baseFileForm) {
        Page page = new Page(baseFileForm.getCurrent(), baseFileForm.getSize());
        String fileName = baseFileForm.getFileName();
        Date start = baseFileForm.getUploadTimeStart();
        Date end = baseFileForm.getUploadTimeEnd();
        LambdaQueryWrapper<BaseFile> lqw = new LambdaQueryWrapper();
        lqw.likeRight(StringUtils.isNotBlank(fileName), BaseFile::getFileName, fileName);
        if (start != null && end != null) {
            lqw.between(BaseFile::getUploadTime, start, end);
        }
        return baseMapper.selectPage(page, lqw);
    }

    @Override
    public void deleteFile(String fileName, String storagePath) {
        Path path = Paths.get(storagePath, fileName);
        try {
            Files.delete(path);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteById (Integer fileId) {
        return removeById(fileId);
    }
}
